package com.bocomm.tracevisualization.global;

import com.bocomm.tracevisualization.api.result.CodeMessage;
import com.bocomm.tracevisualization.api.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

	@ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(value = Exception.class)
	public Result<String> exceptionHanlder(HttpServletRequest request, Exception e) {
		log.error("catch error ", e);
		if (e instanceof BindException) {
			BindException be = (BindException) e;
			List<ObjectError> errors = be.getAllErrors();
			String[] args = new String[errors.size()];
			for (int i = 0; i < errors.size(); i++) {
				args[i] = errors.get(i).getDefaultMessage();
			}
			return Result.fail(CodeMessage.VALIDATE_ERROR.fillArgs(args));
		} else {
			return Result.fail(CodeMessage.SERVER_ERROR);
		}

	}
	@ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(value = BusinessException.class)
	public Result<String> businessExceptionHanlder(HttpServletRequest request, Exception e) {
		log.error("catch error ", e);
		if (e instanceof BusinessException) {
			BusinessException be = (BusinessException) e;
			CodeMessage exceptionId = be.getExceptionId();
			return Result.fail(exceptionId);
		} else {
			return Result.fail(CodeMessage.SERVER_ERROR);
		}

	}
	@ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(value = HttpMessageNotReadableException.class)
	public Result<String> httpMessageNotReadableExceptionHanlder(HttpServletRequest request, Exception e) {
		log.error("catch error ", e);
		if (e instanceof HttpMessageNotReadableException) {
			HttpMessageNotReadableException be = (HttpMessageNotReadableException) e;
			return Result.fail(CodeMessage.VALIDATE_ERROR.fillArgs(be.getMessage()));
		} else {
			return Result.fail(CodeMessage.SERVER_ERROR);
		}

	}
	@ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(value = SchedulerException.class)
	public Result<String> schedulerExceptionHanlder(HttpServletRequest request, Exception e) {
		log.error("catch error ", e);
		if (e instanceof SchedulerException) {
			SchedulerException be = (SchedulerException) e;
			return Result.fail(CodeMessage.SERVER_ERROR.fillArgs(" : "+be.getMessage()));
		} else {
			return Result.fail(CodeMessage.SERVER_ERROR);
		}

	}
}